package com.sgb.kjwl.viewmodel.machine;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.lease.LeaseListEntity;
import com.sgb.kjwl.model.entity.request.LeaseMachineFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.supplier3.MachineDictEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.MachineRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.fragment.machine.MachineListFragment3;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MachineListFragModel3 extends BaseViewModel {
    public ObservableField<LeaseMachineFilterJson> filterJson = new ObservableField<>(new LeaseMachineFilterJson());
    //    public ObservableField<String> areaCode = new ObservableField<>("");
    private MachineListFragment3 fragment;
    private MachineRepertory repertory;
    private int page = 1;
    public int pageSize = 10;

    public MachineListFragModel3(MachineListFragment3 fragment3, MachineRepertory repertory) {
        this.fragment = fragment3;
        this.repertory = repertory;
//        areaCode.set(repertory.getAreaCode());
    }

    public String getAreaNameModel() {
        return repertory.getAreaName();
    }

    public String getAreaCodeModel() {
        return repertory.getAreaCode();
    }

    public void getMachineModel(boolean isLoadMore) {
        page = isLoadMore ? page + 1 : 1;
        filterJson.get().setPageNum(page);
        filterJson.get().setPageSize(pageSize);
        if (repertory.getIsLocal()) {
            //经度
            filterJson.get().setLatitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
            //纬度
            filterJson.get().setLongitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
        } else {
            //经度
            filterJson.get().setLongitude(repertory.getLongititude());
            //纬度
            filterJson.get().setLatitude(repertory.getLatitude());
        }
        //获取租赁手动定位缓存
        String distance_latitude = SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude", "");
        String distance_longitude = SharedPreferenceUtil.getInstance().getSaveStringData("distance_longitude", "");
        if (!TextUtils.isEmpty(distance_latitude) && !TextUtils.isEmpty(distance_longitude)) {
            filterJson.get().setLatitude(distance_latitude);
            filterJson.get().setLongitude(distance_longitude);
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().rentalAndEmployedHall(filterJson.get()).enqueue(new ICallBack<BaseEntity<ListResponse<List<LeaseListEntity>>>>() {

            @Override
            public void onSuccess(BaseEntity<ListResponse<List<LeaseListEntity>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getData() != null) {
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    fragment.showList(new ArrayList<>(), isLoadMore);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<LeaseListEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                fragment.showList(new ArrayList<>(), isLoadMore);
            }
        });
    }

//
//    @SuppressLint("CheckResult")
//    public void getFilterTypeModel() {
//        repertory.getMachineFilterType()
//                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
//                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment.showTypePopWindow(listBaseEntity.getData());
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
//                    }
//                });
//    }

    //获取顶部分类
    public void getFilterTypeModel(String type) {
        APIManager.getInstance().getLeaseMapAPI().getFistcategory(type).enqueue(new Callback<BaseEntity<List<DictEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<DictEntity3>>> call, Response<BaseEntity<List<DictEntity3>>> response) {
                if (response.body() == null || response.body().getState() == null) return;
                if (APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    fragment.showTypePopWindow(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<DictEntity3>>> call, Throwable t) {
            }
        });

    }

    @SuppressLint("CheckResult")
    public void getFilterModelModel(String id) {
        repertory.getMachineFilterModel(id)
                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
                    @Override
                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment.showModelPopWindow(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }
//
//    @SuppressLint("CheckResult")
//    public void getFilterTime() {
//        repertory.getMachineFilterTime()
//                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
//                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment3.showTimePopWindow(listBaseEntity.getData());
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
//                    }
//                });
//    }

//    @SuppressLint("CheckResult")
//    public void getMachineAreaModel() {
//        repertory.getAreaSecondAndThird(repertory.getAreaCode())
//                .subscribe(new Consumer<BaseEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<ParentAreaEntity<List<ParentAreaEntity>>>> listBaseEntity) throws Exception {
//                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment3.showAreaPop(listBaseEntity.getData());
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        MLog.d(AppConstant.API_LOG, throwable.getMessage());
//                    }
//                });
//    }

//    public void getCityData() {
//        APIManager.getInstance().getMachineAPI().getAreaSecondAndThird2(repertory.getAreaCode()).enqueue(new Callback<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>() {
//            @Override
//            public void onResponse(Call<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>> call, Response<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>> response) {
//                if (response.body() == null || response.body().getState() == null) {
//                    return;
//                }
//
//                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
//                    fragment.showAreaPop(response.body().getData());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>> call, Throwable t) {
//
//            }
//        });
//    }

    /**
     * 获取省市区地址
     */
    public void getCityData() {
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null && data.size() > 0) {
                    fragment.showAddressDatas(data, repertory.getAreaCode());
                }
            }
        });
    }

    public void getFilterSort() {
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getLeaseHomeSortWay().enqueue(new Callback<BaseEntity<List<DictEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<DictEntity3>>> call, Response<BaseEntity<List<DictEntity3>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showSortPopWindow(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<DictEntity3>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

//    @SuppressLint("CheckResult")
//    public void getFilterSpec(String id) {
//        repertory.getMachineFilterSpec(id)
//                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
//                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment3.showFilterSpec(listBaseEntity.getData());
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
//                    }
//                });
//    }

    /**
     * 获取属性筛选列表
     */
    public void getFilterSpec(String categoryNo, String typeNo) {
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...", 0, false).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getAttributeList(categoryNo, typeNo).enqueue(new Callback<BaseEntity<List<MachineDictEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<MachineDictEntity>>> call, Response<BaseEntity<List<MachineDictEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showFilterSpec(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<MachineDictEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    public void getH5Url(String type, String id) {
        String name = "";
        if ("1".equals(type)) {
            name = "mechanicsDetail";//机械
        } else if ("2".equals(type)) {
            name = "equipmentDetails";//设备
        } else if ("3".equals(type)) {
            name = "vehicleDetails";//车辆
        } else if ("4".equals(type)) {
            name = "propertyDetails";//房产
        } else if ("5".equals(type)) {
            name = "landDetails";//土地
        } else if ("6".equals(type)) {
            name = "factoryDetails";//工厂
        } else if ("7".equals(type)) {
            name = "farmDetail";//农机
        }
        if (TextUtils.isEmpty(name)) {
            return;
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(name).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id + "&iosFlag=1";
//                    WebViewX5HostActivity.start(fragment.getActivity(), url);
                    WebViewX5HostActivity.start(fragment.getActivity(), url, id, "lease", type);
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
